package com.davy.gridpoint.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.davy.gridpoint.BaseActivity;
import com.davy.gridpoint.R;
import com.davy.gridpoint.http.HttpClient;
import com.davy.gridpoint.qlxj.TakeActivity;
import com.davy.gridpoint.qlxj.adapter.JcbhAdapter;
import com.davy.gridpoint.utils.AudioRecorder;
import com.davy.gridpoint.utils.LogUtils;
import com.davy.gridpoint.utils.StringUtils;
import com.davy.gridpoint.utils.ToastUtil;
import com.davy.gridpoint.view.CustomImageView;
import com.davy.gridpoint.view.MyRecyclerView;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class DemoActivity extends BaseActivity {
    private MyRecyclerView recyclerBing;
    private JcbhAdapter jcbhAdapter;
    private ArrayList<Map> bhList;
    private final int REQUEST_IMG = 1001;
    private final int REQUEST_VIDEO = 1002;
    private final int REQUEST_VIDEO_QUAN = 1003;
    private final int REQUEST_LY_QUAN = 1004;
    private VideoView videoView;
    private ImageView tvViewClose;
    private LinearLayout lyVideo;

    @Override
    protected void onStart() {
        super.onStart();
        /*// 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.MANAGE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.MANAGE_EXTERNAL_STORAGE}, 1001);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                Intent appIntent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                appIntent.setData(Uri.parse("package:" + getPackageName()));
                try {
                    mContext.startActivity(appIntent);
                } catch (ActivityNotFoundException ex) {
                    ex.printStackTrace();
                    Intent allFileIntent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                    mContext.startActivity(allFileIntent);
                }
            }
        }*/
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_demo);
        statusbar4();
        bhList = new ArrayList<>();
        recyclerBing = findViewById(R.id.recyclerBing);
        lyVideo = findViewById(R.id.lyVideo);
        videoView = findViewById(R.id.videoView);
        tvViewClose = findViewById(R.id.tvViewClose);
        tvViewClose.setOnClickListener(v -> {
            if (videoView != null) {
                // 当你需要停止播放时，调用stopPlayback()方法
                videoView.stopPlayback();
            }
            lyVideo.setVisibility(View.GONE);
        });
        // 设置播放完成监听器
        videoView.setOnCompletionListener(mp -> {
            // 视频播放结束时的操作
            new Handler().postDelayed(() -> {
                if (videoView != null) {
                    videoView.stopPlayback();
                }
                lyVideo.setVisibility(View.GONE);
            }, 300);
        });


        recyclerBing.setLayoutManager(new GridLayoutManager(mContext, 4, RecyclerView.VERTICAL, false));
        jcbhAdapter = new JcbhAdapter(mContext, bhList);
        recyclerBing.setAdapter(jcbhAdapter);
        jcbhAdapter.setItemClickListener(new JcbhAdapter.ItemClickListener() {
            @Override
            public void addClick(int position) {
                if (StringUtils.isFastClick()) {
                    return;
                }
                xuanDialog();
            }

            @Override
            public void delClick(int position, Map mList) {
                if (StringUtils.isFastClick()) {
                    return;
                }
                bhList.remove(position);
                jcbhAdapter.setData(bhList);
//                SPUtils.setDataList(mContext, "jc_" + rw_id + "_" + device_id + "_" + check_id, bhList);
            }

            @Override
            public void getClick(int position, Map mList) {
                if (StringUtils.isFastClick()) {
                    return;
                }

                int type = Double.valueOf(StringUtils.isEmpty(mList.get("type") + "") ? "0" : mList.get("type") + "").intValue();
                if (type == 1 || type == 2) {
                    String img = mList.get("img") + "";
                    Double isBt = 1.0; //1：保存 2：提交
                    if (mList.containsKey("isBt")) {
                        isBt = Double.valueOf(mList.get("isBt") + "");
                    }

                    if (isBt.intValue() == 2) {
                        if (!img.startsWith("http")) {
                            img = HttpClient.imgUrl + img.replace("/storage/emulated/0/Davy/", "");
                        }
                    }

                    if (type == 2) {
                        lyVideo.setVisibility(View.VISIBLE);
                        try {
                            videoView.setVideoPath(img);
                            videoView.setOnPreparedListener(mp -> {
                            });
                            videoView.start();
                        } catch (Exception e) {
                            LogUtils.d("TAG", "e:" + e.toString());
                        }
                    } else {
                        imgDialog(img);
                    }
                }
                if (type == 3) {
                    boDialog(mList);
                }
            }
        });

    }


    public void xuanDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_xuan, null);
        AppCompatButton btnPz = v.findViewById(R.id.btnPz);
        AppCompatButton btnPsp = v.findViewById(R.id.btnPsp);
        AppCompatButton btnLy = v.findViewById(R.id.btnLy);
        AppCompatButton tvClose = v.findViewById(R.id.tvClose);
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(true);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);

        //自定义的东西
        dialog.getWindow().setContentView(v);
        tvClose.setOnClickListener(v1 -> dialog.dismiss());

        btnPz.setOnClickListener(view -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            Intent intent = new Intent(mContext, TakeActivity.class);
            startActivityForResult(intent, REQUEST_IMG);
            dialog.dismiss();
        });
        btnPsp.setOnClickListener(view -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(DemoActivity.this, new String[]{Manifest.permission.CAMERA}, REQUEST_VIDEO_QUAN);
            } else {
                openCamera();
            }

            dialog.dismiss();
        });
        btnLy.setOnClickListener(view -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(DemoActivity.this, new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_LY_QUAN);
            } else {
                lyDialog();
            }

            dialog.dismiss();
        });
    }

    private long startTime;
    private AudioRecorder recorder;
    private String filePath;
    private MediaPlayer mediaPlayer;

    private void openCamera() {
        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
            // 设置视频质量
            takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            //允许记录的最长时间(以 秒 为单位)  例如：限制为60S
            takeVideoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 60);
            // 设置输出文件的最大大小
            takeVideoIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 1024L * 1024 * 100);
//            takeVideoIntent.setAction("android.media.action.VIDEO_CAPTURE");
//            takeVideoIntent.addCategory("android.intent.category.DEFAULT");
//            takeVideoIntent.addCategory("android.intent.extra.videoQuality");
            startActivityForResult(takeVideoIntent, REQUEST_VIDEO);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    public void lyDialog() {
        startTime = 0;
        filePath = "";
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        AlertDialog dialog = builder.create();
        // 显示对话框前，设置全屏
        dialog.setOnShowListener(d -> {
            // 获取对话框窗口
            Window window = dialog.getWindow();
            if (window != null) {
                // 设置窗口的属性以全屏显示
                window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
                window.setBackgroundDrawableResource(android.R.color.transparent);
                window.setGravity(Gravity.BOTTOM);
            }
        });
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_luyin, null);
        ImageView tvClose = v.findViewById(R.id.tvClose);
        TextView tvDelete = v.findViewById(R.id.tvDelete);
        TextView tvSave = v.findViewById(R.id.tvSave);
        AppCompatButton tvAudios = v.findViewById(R.id.tvAudios);
        ImageView imgAudio = v.findViewById(R.id.imgAudio);
        dialog.setCanceledOnTouchOutside(true);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        imgAudio.setImageDrawable(mContext.getResources().getDrawable(R.drawable.icon_gif_yp));
        //自定义的东西
        dialog.getWindow().setContentView(v);
        tvAudios.setOnTouchListener((v14, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (!StringUtils.isEmpty(filePath)) {
                        deleteVideo(filePath);
                    }
                    // 按下事件
                    startTime = System.currentTimeMillis();
                    Glide.with(mContext).asGif().load(R.drawable.icon_gif_yp).into(imgAudio);
                    filePath = Environment.getExternalStorageDirectory() + "/Davy/" + "grid_audio_" + System.currentTimeMillis() + ".3gp";
                    recorder = new AudioRecorder(filePath);
                    try {
                        recorder.startRecording();
                    } catch (IOException e) {
                        // 处理IOException
                        LogUtils.e("TAG", "e:" + e.toString());
                    }
                    tvAudios.setText("正在录音，松开后保存");
                    break;
                case MotionEvent.ACTION_UP:
                    // 松开事件
                    long duration = System.currentTimeMillis() - startTime;
                    LogUtils.e("TAG", "------------>" + ViewConfiguration.getLongPressTimeout());
                    if (duration >= ViewConfiguration.getLongPressTimeout()) {
                        // 长按事件
                        recorder.stopRecording();
                        // 录音结束，文件保存在指定路径
                        tvAudios.setText("录音完成");

                        new Handler().postDelayed(() -> {
                            Map dataMap = new HashMap();
                            dataMap.put("isBt", 1);//1：未提交 2：提交
                            dataMap.put("p_time", StringUtils.getTimeS());
                            dataMap.put("img", filePath);
                            dataMap.put("type", 3);
                            bhList.add(dataMap);
                            jcbhAdapter.setData(bhList);

                            dialog.dismiss();
                        }, 800);
                    } else {
                        deleteVideo(filePath);
                        filePath = "";
                        tvAudios.setText("按住 录音");
                        // 非长按事件
                    }
                    imgAudio.setImageDrawable(mContext.getResources().getDrawable(R.drawable.icon_gif_yp));
                    if (recorder != null) {
                        recorder = null;
                    }
                    break;
            }
            return true;
        });
        dialog.setOnCancelListener(dialog1 -> {
            if (!StringUtils.isEmpty(filePath)) {
                deleteVideo(filePath);
            }
            dialog1.dismiss();
        });
        tvDelete.setOnClickListener(v12 -> {
            if (!StringUtils.isEmpty(filePath)) {
                deleteVideo(filePath);
            }
            dialog.dismiss();
        });
        tvClose.setOnClickListener(v1 -> {
            if (!StringUtils.isEmpty(filePath)) {
                deleteVideo(filePath);
            }
            dialog.dismiss();
        });
        tvSave.setOnClickListener(v13 -> {
            if (StringUtils.isEmpty(filePath)) {
                ToastUtil.showNew(mContext, "请录音或录音太短");
                return;
            }
            if (StringUtils.isFastClick()) {
                return;
            }
            Map dataMap = new HashMap();
            dataMap.put("isBt", 1);//1：未提交 2：提交
            dataMap.put("p_time", StringUtils.getTimeS());
            dataMap.put("img", filePath);
            dataMap.put("type", 3);
            bhList.add(dataMap);
            jcbhAdapter.setData(bhList);

            dialog.dismiss();
        });
    }

    public void boDialog(Map mList) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        AlertDialog dialog = builder.create();
        // 显示对话框前，设置全屏
        dialog.setOnShowListener(d -> {
            // 获取对话框窗口
            Window window = dialog.getWindow();
            if (window != null) {
                // 设置窗口的属性以全屏显示
//                window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
                window.setBackgroundDrawableResource(android.R.color.transparent);
                window.setGravity(Gravity.CENTER);
            }
        });
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_ly_bo, null);
        ImageView tvClose = v.findViewById(R.id.tvClose);
        ImageView imgAudio = v.findViewById(R.id.imgAudio);
        dialog.setCanceledOnTouchOutside(true);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        imgAudio.setImageDrawable(mContext.getResources().getDrawable(R.drawable.icon_gif_yp));
        //自定义的东西
        dialog.getWindow().setContentView(v);
        Glide.with(mContext).asGif().load(R.drawable.icon_gif_yp).into(imgAudio);

        mediaPlayer = new MediaPlayer();

        try {
            // 假设音频文件位于内部存储中，文件路径为"path/to/your/audio/file.mp3"
            String filePath = mList.get("img") + "";

            Double isBt = 1.0;//1：保存 2：提交
            if (mList.containsKey("isBt")) {
                isBt = Double.valueOf(mList.get("isBt") + "");
            }

            if (isBt.intValue() == 2) {
                if (!filePath.startsWith("http")) {
                    filePath = HttpClient.imgUrl + filePath.replace("/storage/emulated/0/Davy/", "");
                }
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.setDataSource(filePath);
            } else {
                mediaPlayer.setDataSource(DemoActivity.this, Uri.parse("file://" + filePath));
                mediaPlayer.prepare();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        mediaPlayer.start();

        mediaPlayer.setOnCompletionListener(mp -> {
            new Handler().postDelayed(() -> {
                // 播放结束后的操作
                if (mediaPlayer != null) {
                    // 在需要停止并释放资源的时候
                    mediaPlayer.stop(); // 停止播放
                    mediaPlayer.release(); // 释放资源
                }

                dialog.dismiss();
            }, 300);
        });

        dialog.setOnCancelListener(dialog1 -> {
            if (mediaPlayer != null) {
                // 在需要停止并释放资源的时候
                mediaPlayer.stop(); // 停止播放
                mediaPlayer.release(); // 释放资源
            }

            dialog1.dismiss();
        });
        tvClose.setOnClickListener(v1 -> {
            if (mediaPlayer != null) {
                // 在需要停止并释放资源的时候
                mediaPlayer.stop(); // 停止播放
                mediaPlayer.release(); // 释放资源
            }

            dialog.dismiss();
        });
    }

    public void imgDialog(String milepostStr) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext);
        android.app.AlertDialog dialog = builder.create();
        // 显示对话框前，设置全屏
        dialog.setOnShowListener(d -> {
            // 获取对话框窗口
            Window window = dialog.getWindow();
            if (window != null) {
                // 设置窗口的属性以全屏显示
                window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                window.setBackgroundDrawableResource(android.R.color.transparent);
            }
        });

        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_img_item, null);
        ImageView tvClose = v.findViewById(R.id.tvClose);
        CustomImageView imgYu1 = v.findViewById(R.id.imgYu1);
        dialog.setCanceledOnTouchOutside(true);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        //自定义的东西
        dialog.getWindow().setContentView(v);

        Glide.with(mContext).load(milepostStr).error(R.mipmap.icon_error).into(imgYu1);

        tvClose.setOnClickListener(v1 -> dialog.dismiss());
    }

    public boolean deleteVideo(String videoPath) {
        File videoFile = new File(videoPath);

        // 检查文件是否存在和是否是文件
        if (videoFile.exists() && videoFile.isFile()) {
            return videoFile.delete();
        }
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (lyVideo.getVisibility() == View.VISIBLE) {
                lyVideo.setVisibility(View.GONE);
                if (videoView != null) {
                    // 当你需要停止播放时，调用stopPlayback()方法
                    videoView.stopPlayback();
                }
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_IMG) {
                Bundle extras = data.getExtras();
                Map dataMap = new HashMap();
                dataMap.put("isBt", 1);//1：未提交 2：提交
                dataMap.put("p_time", StringUtils.getTimeS());
                dataMap.put("img", extras.get("data"));
                dataMap.put("type", 1);
                bhList.add(dataMap);
                jcbhAdapter.setData(bhList);
            }
            if (requestCode == REQUEST_VIDEO_QUAN) {
                openCamera();
            }
            if (requestCode == REQUEST_VIDEO) {
                Uri videoUri = data.getData();
                LogUtils.e("TAG", "videoUri:" + videoUri.toString());
                // 视频文件的完整路径
                String videoPath = getPathFromUri(videoUri);
                LogUtils.e("TAG", "videoPath:" + videoPath.toString());

                Map dataMap = new HashMap();
                dataMap.put("isBt", 1);//1：未提交 2：提交
                dataMap.put("p_time", StringUtils.getTimeS());
                dataMap.put("img", videoPath);
                dataMap.put("type", 2);
                bhList.add(dataMap);
                jcbhAdapter.setData(bhList);
            }
        }
    }

    public String getPathFromUri(Uri uri) {
        Cursor cursor = null;
        String path = null;
        try {
            String[] projection = {MediaStore.Video.Media.DATA};
            cursor = getContentResolver().query(uri, projection, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
                path = cursor.getString(column_index);
            }
        } finally {
            if (cursor != null) cursor.close();
        }
        return path;
    }
}
